import asyncio
from bleak import BleakClient, BleakScanner, BleakGATTCharacteristic
from flask import Flask, jsonify

value = 0
deviceList = []
app = Flask(__name__)
linkStatus = False


async def selectBle():
    scanner = BleakScanner()
    await scanner.start()

    devices = await BleakScanner.discover()
    global deviceList
    deviceList.clear()

    for device in devices:
        if device.name is not None:
            print(f"Found device: {device.name} - {device.address}")
            deviceList.append({device.name: device.address})

    await scanner.stop()


async def linkBle(address):

    # 基于MAC地址查找设备
    device = await BleakScanner.find_device_by_address(
        address, cb=dict(use_bdaddr=False)
    )
    if device is None:
        print("could not find device with address '%s'", address)
        return
    # 事件定义
    disconnected_event = asyncio.Event()

    # 连接状态
    global linkStatus

    # 连接设备
    print("connecting to device...")
    async with BleakClient(device) as client:
        print("Connected")
        await client.start_notify("00002a37-0000-1000-8000-00805f9b34fb", notification_handler)
        await disconnected_event.wait()  # 休眠直到设备断开连接，有延迟。此处为监听设备直到断开为止
        linkStatus = False


# 处理接收到的数据
def notification_handler(characteristic: BleakGATTCharacteristic, data: bytearray):
    global value
    value = int(data.hex().split('06')[1], 16)
    global linkStatus
    linkStatus = True


# 搜索附近蓝牙设备
@app.route('/selectBle', methods=['GET'])
def select_ble():
    asyncio.run(selectBle())
    return jsonify("tryScan")


# 获取搜索到的蓝牙设备列表
@app.route('/getDeviceList', methods=['GET'])
def device_list():
    return jsonify(deviceList)


# 连接蓝牙设备
@app.route('/linkBle/address/<mac>', methods=['GET'])
def link_ble(mac):
    result = asyncio.run(linkBle(mac))
    return jsonify(result)


# 获取蓝牙设备的心率数据
@app.route('/getHeartNum', methods=['GET'])
def heart_num():
    return jsonify(value)


if __name__ == "__main__":
    app.run(debug=True, port=9365)
